<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Model\AdminMenu;
use App\Service\AdminLoginService;
use App\Service\AdminLogService;
use App\Service\AdminPermissionService;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;

class AdminMiddleware implements MiddlewareInterface {

    protected RequestInterface $request;
    protected HttpResponse $response;

    public function __construct(RequestInterface $request, HttpResponse $response) {
        $this->request = $request;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {

        // 获取配置【根据路由获取配置】
        $router = trim($this->request->getPathInfo(), '/');
        $routerConfig = AdminMenu::query()->where('url', $router)->first();

        if (!is_null($routerConfig)) {
            try {
                if ($routerConfig->getAttribute('auth')) {
                    new AdminLoginService($this->request);
                }
                if ($routerConfig->getAttribute('permission')) {
                    new AdminPermissionService($router);
                }
                if ($routerConfig->getAttribute('log')) {
                    new AdminLogService($this->request, $routerConfig);
                }
            } catch (RuntimeException $e) {
                return $this->response->json(
                    [
                        'code' => $e->getCode(),
                        'msg'  => $e->getMessage(),
                        'data' => []
                    ]
                );
            }
        } else {
            return $this->response->json(
                [
                    'code' => ErrorCode::INVALID,
                    'msg'  => '当前路由非法：' . $this->request->getPathInfo(),
                    'data' => []
                ]
            );
        }

        return $handler->handle($request);
    }
}
